package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"news/cache"
	"news/models"
)

type NewsController struct {
	beego.Controller
}

func (c *NewsController) Add() {
	name := c.GetString("name")
	title := c.GetString("title")
	area := c.GetString("area")
	address := c.GetString("address")
	var news models.News
	news.Name = name
	news.Title = title
	news.Area = area
	news.Address = address
	if news.Add() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	key, _ := news.List()
	keys, _ := json.Marshal(key)
	cache.Rdb.Set(cache.Ctx, "list_add", keys, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
}
func (c *NewsController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	title := c.GetString("title")
	area := c.GetString("area")
	address := c.GetString("address")
	var news models.News
	news.ID = uint(id)
	news.Name = name
	news.Title = title
	news.Area = area
	news.Address = address
	if news.Update() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "修改失败",
		}
		c.ServeJSON()
		return
	}
	key, _ := news.List()
	keys, _ := json.Marshal(key)
	cache.Rdb.Set(cache.Ctx, "list_Update", keys, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "修改成功",
	}
	c.ServeJSON()
}
func (c *NewsController) Del() {
	id, _ := c.GetInt("id")
	var news models.News
	news.ID = uint(id)
	if news.Del() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}
	key := fmt.Sprintf("news_del_%d", id)
	keys, _ := json.Marshal(news)
	cache.Rdb.Set(cache.Ctx, key, keys, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
}
func (c *NewsController) List() {
	JsonRData := cache.Rdb.Get(cache.Ctx, "list_news").Val()
	var news []*models.News
	if JsonRData == "" {
		models.DB.Find(&news)
		Redis, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, "list_news", Redis, 0)
	} else {
		fmt.Println("使用缓存")
		json.Unmarshal([]byte(JsonRData), &news)
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "查询成功",
		"data": news,
	}
	c.ServeJSON()
}
